package gov.child.web.controller;

import gov.child.entities.vo.Auth;
import gov.child.entities.vo.User;
import gov.child.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author fzh
 * @since 2017/9/11
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/doRegister")
    public String doRegister(@RequestParam String username, @RequestParam String password, @RequestParam String phone) {
        userService.save(username, password, phone);
        return "redirect:/";
    }

    @PostMapping("/login")
    public String doLogin(Auth auth, Model model, HttpSession session) {
        User user = userService.find(auth);
        Objects.requireNonNull(user, "User must not be null here.");
        if (user.equals(User.EMPTY_USER_INFO)) {
            model.addAttribute("msg", "Login Failed");
        } else {
            session.setAttribute("user", user);
        }
        return "forward:/";
    }

    @GetMapping("/logout")
    public String doLogout(HttpSession session) {
        session.invalidate();
        return "redirect:/";
    }

    @GetMapping("/personal")
    public String personal() {
        return "person/person";
    }

    @GetMapping("/events")
    public String events() {
        return "person/all_events";
    }

    @PostMapping("/update")
    public String updateInfo(User user, HttpSession session) {
        if (userService.update(user)) session.setAttribute("user", user);
        return "person/person";
    }

}
